package hu.issue.framework.web.tag;

import hu.issue.framework.web.Constants;
import hu.issue.framework.web.validation.ErrorMessages;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class FormTag extends BodyTagSupport {

	@Override
	public int doStartTag() throws JspException {
		this.pageContext.getRequest().setAttribute("odd", 1);
		final JspWriter writer = this.pageContext.getOut();
		try {
			writer.println("<form method=\"post\">");
		} catch (final IOException e) {
			throw new JspException(e);
		}
		final ErrorMessages messages = (ErrorMessages) this.pageContext.getAttribute(Constants.FORM_ERROR, PageContext.REQUEST_SCOPE);
		ErrorRenderer.render(messages, new PrintWriter(writer));
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		this.pageContext.getRequest().removeAttribute("odd");
		final JspWriter writer = this.pageContext.getOut();
		try {
			writer.println("</form>");
		} catch (final IOException e) {
			throw new JspException(e);
		}

		return EVAL_PAGE;
	}
}
